#include "ToolCreateLine.h"
#include "GraphicsView.h"
#include "GraphicsScene.h"
#include "GraphicsLineItem.h"

ToolCreateLine::ToolCreateLine(const QString &icon, const QString &grp)
    : ToolBase(icon, grp), m_scene(nullptr), m_line(nullptr)
    , m_pressedFirst(false)
    , m_pressedSecond(false)
{
}

QString
ToolCreateLine::name() const
{
    return "CreateLine";
}

void
ToolCreateLine::mousePressEvent(GraphicsView *view, QMouseEvent *event)
{
    if(! m_pressedFirst)
    {
//        if(m_line != nullptr)
//        {
//            m_scene->removeItem(m_line);\
//            delete m_line;
//        }
//        m_scene = view->scene();
        m_line = new GraphicsLineItem();
        double x = -1.0 + (double)event->x()/(double)view->width() * 2.0 ;
        double y = 1.0 - (double)event->y()/(double)view->height() * 2.0;
        m_line->setHead(QPointF(x,y));
        m_line->setTail(QPointF(x, y));
        view->addItem(m_line);
        m_pressedFirst = true;
    }
    else
    {
        m_pressedSecond = true;
    }
}

void
ToolCreateLine::mouseMoveEvent(GraphicsView *view, QMouseEvent *event)
{
    if(m_pressedFirst && ! m_pressedSecond)
    {

        double x = -1.0 + (double)event->x()/(double)view->width() * 2.0 ;
        double y = 1.0 - (double)event->y()/(double)view->height() * 2.0;

        qDebug() << event->x() << event->y() << x << y << view->width() << view->height();
        m_line->setTail(QPointF(x, y));
        event->accept();
    }
}

void
ToolCreateLine::mouseReleaseEvent(GraphicsView *view, QMouseEvent *event)
{
    if(m_pressedFirst && m_pressedSecond)
    {
        //

        view->removeItem(m_line);
        m_line = nullptr;
        m_pressedFirst = m_pressedSecond = false;
        event->accept();
    }
}
